<template>
  <div class="page-container">
    <el-row class="book-info-container">
      <!-- 图书封面 -->
      <el-col :span="6" class="book-cover-container">
        <!-- <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6"> -->
        <div class="book-cover">
          <!-- <img :src="book.coverUrl" @error="handleImageError" alt="图书封面" /> -->
          <img :src="book.coverUrl ? book.coverUrl : nullImageUrl" @error="handleImageError" alt="图书封面" />
          <!-- <img v-else :src="nullImageUrl" alt="暂无图片" /> -->
        </div>
      </el-col>
      <!-- 图书详情 -->
      <el-col :span="17" class="book-detail-container">
        <!-- <el-col :xs="24" :sm="18" :md="18" :lg="18" :xl="18"> -->
        <el-row>
          <el-col :span="24" class="book-title-author-publisher">
            <el-row>
              <el-col>
                <span class="book-title">《{{ book.title }}》</span>
              </el-col>
            </el-row>
            <el-row>
              <el-col class="book-isbn">
                <p>ISBN:{{ book.isbn ? book.isbn : '未知' }}</p>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <span class="book-author">作者：{{ book.author }}</span>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <span class="book-publisher">出版社：{{ book.publisher ? book.publisher : '未知'
                }}</span>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" class="book-intro">
            <p>商品介绍：{{ book.description }}</p>
          </el-col>
        </el-row>



        <el-row>
          <el-col :span="8" class="book-price-box">
            单价： <span class="book-price">{{ book.price }}</span>
          </el-col>
        </el-row>

        <el-row class="book-stock-box">
          <el-col :span="8" class="book-stock">
            <p>库存：{{ book.stock }}</p>
          </el-col>
        </el-row>



        <el-row>
          <el-col :span="6" class="book-count">
            <el-input-number v-model="count" :min="1" :max="book.stock" />
          </el-col>

          <el-col :span="6" class="add-cart-btn">
            <el-button type="primary" @click="addToCart">加入购物车</el-button>
          </el-col>
          <!-- <el-row> -->

          <!-- </el-row> -->
          <el-col :span="6" class="buy-btn">
            <el-button type="danger" @click="buy">购买</el-button>
          </el-col>
          <el-col :span="6" v-if="book.price !== undefined && count !== undefined" class="book-total-price-box">
            总价：<span class="book-total-price">{{ totalAmountBuyNowDetail(book.price, count) }}</span>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

  </div>
  <PaymentDialog :book="book" :payWay="'立即购买'" :count="count" v-model:dialogVisible="centerDialogVisible">
  </PaymentDialog>
</template>

<script setup>
import { ref } from 'vue';
import { onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router';
import { addCart } from '@/api/cart'
import { getBookDetail } from '@/api/book';
import { Decimal } from 'decimal.js'
import PaymentDialog from '@/components/order/PaymentDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { useUserStore } from '@/stores/user'
const userStore = useUserStore();

//立即购买的商品价格
const totalAmountBuyNowDetail = (priceNum, countNum) => {
  const price = new Decimal(priceNum.toString());
  const quantity = new Decimal(countNum.toString());
  return price.times(quantity).toFixed(2);
};

// 使用 Vite 的 URL 解析方式处理静态资源
const defaultImageUrl = new URL('../../assets/error2.png', import.meta.url).href;
const nullImageUrl = new URL('../../assets/noPicture.jpg', import.meta.url).href;

// 处理图片加载失败事件
const handleImageError = (event) => {
  // 直接设置为默认图片
  event.target.src = defaultImageUrl;

  console.log('图片加载失败，已替换为默认图');
};

const book = ref({});
const route = useRoute();
const router = useRouter();
onMounted(async () => {
  // 获取url中的参数
  const bookId = route.params.bookId;
  console.log(bookId, '->route.params.bookId');
  // 请求后端接口获取图书详情数据
  const res = await getBookDetail(bookId);
  if (res.data.code === 0) {
    book.value = res.data.data;
  }
  console.log("请求后端接口获取图书详情数据", book.value);
});

// 选择的数量 
const count = ref(1);

const addToCart = async () => {
  // console.log(`已将《${book.value.title}》共 ${count.value} 本加入购物车`);
  // 实际可在此处编写调用接口加入购物车等逻辑
  if (userStore.isLoggedIn === false) {
    ElMessage({
      type: 'error',
      message: '请先登录',
      plain: true
    })
    router.push({
      path: '/login'
    });
    return;
  }
  ElMessageBox.alert(`《${book.value.title}》×${count.value} 确定加入到购物车？`, '提示', {
    confirmButtonText: '确定',
    callback: async (action) => {

      if (action === 'confirm') {

        const bookData = { bookId: book.value.bookId, quantity: count.value }
        console.log("加入购物车请求参数：", bookData);
        const result = await addCart(bookData);
        console.log("!加入购物车请求", result);

        if (result.data.code === 0) {
          ElMessage({
            type: 'success',
            message: "加入购物车成功",
            plain: true

          })
        } else {
          ElMessage({
            type: 'error',
            message: result.data.message,
            plain: true

          })
        }
        console.log("加入购物车请求结果：", result);
      } else {
        ElMessage({
          type: 'warning',
          message: "取消加入购物车",
        })
      }
    }
  })


};


// 弹窗相关____________
const centerDialogVisible = ref(false)
// 与购买相关
const buy = () => {
  if (!userStore.isLoggedIn) {
    ElMessage({
      type: 'error',
      message: '请先登录',
      plain: true
    })
    router.push({
      path: '/login'
    });
    return;
  } else {
    // console.log(`购买内容《${props.book.title}》共 ${count.value} 本`);
    //弹窗让用户写下订单信息
    centerDialogVisible.value = true;
  }


};


</script>

<style scoped>
.book-info-container {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin: 20px 0;
}


.book-cover {
  width: 90%;
  height: 100%;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  /* overflow: hidden; */
  /* border: 3px solid #4d4d4d; */
  box-shadow: 0 0 3px #999;
}

.book-title-author-publisher {
  padding: 10px 0;
}

.book-title {
  font-size: 32px;
  font-weight: bold;
  margin-right: 20px;
}

.book-author,
.book-publisher {
  margin-right: 20px;
  color: #666;
}

.book-intro {
  padding: 10px 0;
  color: #333;

}

.book-isbn,
.book-price {
  padding: 10px 0;
  font-size: 20px;
}

.book-price,
.book-total-price {
  color: rgb(231, 9, 9);
  font-size: 22px;
}

.book-price-box,
.book-stock-box,
.book-total-price-box {
  font-size: 18px;
}

.book-count,
.add-cart-btn,
.buy-btn {
  padding: 10px 0;
}
</style>
